package cn.itcast.bos.web.action.base;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;

import cn.itcast.bos.domain.base.Standard;
import cn.itcast.bos.service.StandartService;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.util.ValueStack;


@Controller  // 这个类由spring来管理
@Scope("prototype")
@ParentPackage("json-default")
@Namespace("/")
@Actions
public class StandartAction  extends ActionSupport implements ModelDriven<Standard>{

	private int page;
	private int rows;
	public void setPage(int page) {
		this.page = page;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}


	Standard standard = new Standard();
	@Override
	public Standard getModel() {
		return standard;
	}

	
	@Autowired
	private StandartService standartService;
	
	@Action(value="standard_save",results={@Result(name="success",location="./pages/base/standard.html",type="redirect")})
	public String  save(){
		standartService.save(standard);
		System.out.println("添加成功");
		return "success";
	}
	
	// 分页查询数据
	
	@Action(value="standard_pageQuery",results={@Result(name="success",type="json")})
	public String pageQuery(){
		// 默认页数从0开始
		Pageable pageAble  = new PageRequest(page - 1, rows);
		
		Page<Standard> page = standartService.findPageData(pageAble);
		
		// 将数据保存到一个map集合中，然后前端读取的是一个json，json中两个元素，rows和total：data.json
		Map<String ,Object> map = new HashMap<String ,Object>();
		map.put("total", page.getTotalElements());
		map.put("rows", page.getContent());
		
		// 将数据保存到值栈中
		ActionContext.getContext().getValueStack().push(map);
		System.err.println("====================================================");
		System.err.println(map);
		
		return "success";
		
	}
	
	
	// 显示快递员取派标准下拉列表
	@Action(value="standard_findAll",results={@Result(name="success",type="json")})
	public String findAll(){
		
		
		// 调用业务层方法
		List<Standard> list = standartService.findAll();
		
		// 将数据保存到值栈当中
		ActionContext.getContext().getValueStack().push(list);
		
		return "success";
	}
	
	
	
	
	
	
}
